#! /bin/bash

HAND="[*] "
SKIP="--- "
TAB="    "
SVN="/usr/bin/svn"
LOG="/var/log/`basename $0`.`hostname`.log"

#=========================================================================

last_rev=""
curr_rev=""
last_repo=""
last_call=""
last_update=""


function proc_pid(){
    ps -elf | grep "`basename $0`" | grep background | grep -v grep | awk '{print $4}' | head -n 1
    return 0
}

function get_url()
{
    dir_name="$1"
    $SVN info $dir_name 2>/dev/null | awk '( $1 ~ /^URL:/){print $2}'
}

function get_rev()
{
    dir_name="$1"
    $SVN info $dir_name 2>/dev/null | awk '( $1 ~ /^Revision:/){print $2}'
}

function is_svn_repo()
{
  dir_name="$1"

  $SVN info "$dir_name" 1>/dev/null 2>&1
  if [ $? -eq 1 ]
  then
    echo "false"
  else
    echo "true"
  fi

  return 0
}

function svn_log()
{
  dir_name="$1"
  curr_rev="`get_rev $dir_name`"
  if [ "$last_rev" == "$curr_rev" ]
  then
    echo "$TAB No update info [$curr_rev]."
    return 0
  fi

  echo "$TAB Log info from $last_rev to $curr_rev:"
  $SVN log -r $last_rev:$curr_rev $dir_name 2>&1

  last_repo="$dir_name"
  last_update="`date`"
  return 0
}

function svn_up()
{
  dir_name="$1"
  if [ "`is_svn_repo $dir_name`" == "true" ]
  then
    last_rev="`get_rev $dir_name`"
    url="`get_url $dir_name`"
    echo "$HAND svn up \"$dir_name\""
    echo "$TAB $url"
    $SVN up "$dir_name" 2>&1 | sed "s/^/     /g"
    svn_log "$dir_name"
  else
    echo "$SKIP Skipped \"$dir_name\" since it is not a svn repo"
  fi
  return 0
}


function svn_up_all()
{
  echo "[`date +'%Y/%m/%d %H:%M:%S'`]: $1"
  all_dir="$1"
  find "$all_dir" -maxdepth 1 2>/dev/null | while read sub_dir
  do
    if [ -d $sub_dir ]
    then
      svn_up "$sub_dir"
    fi
  done
  echo ""
  return 0
}

svn_up_all "/pbfd/manageability/" >> $LOG
svn_up_all "/pbfd/manageability/smx/" >> $LOG

